package com.kfgj.hkp.common.utils;

import com.kfgj.hkp.common.auth.Token;
import com.kfgj.hkp.common.constants.ContextConstants;
import com.kfgj.hkp.common.logging.Logger;
import com.kfgj.hkp.common.logging.LoggerFactory;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by liwensihan on 2015-11-17.
 *
 * @author liwensihan
 */
public class CookieHelper {

    private Logger logger = LoggerFactory.getLogger(CookieHelper.class);

    public static Cookie getCookie(HttpServletRequest request, String cookieName) {

        if (StringUtils.isEmpty(cookieName)) {
            return null;
        }

        Cookie ck = null;
        Cookie[] cks = request.getCookies();
        if (cks != null && cks.length > 0) {
            for (Cookie c : cks) {
                if (c.getName().equalsIgnoreCase(cookieName)) {
                    ck = c;
                }
            }
        }
        return ck;
    }

    public static void addUserLoginTokenToCookie(HttpServletRequest request,
                                                 HttpServletResponse response,
                                                 Token token) {

        String tkValue = token.toBase64String();

        Cookie ck = getCookie(request, ContextConstants.request_cookie_token);
        if (ck != null) {
            ck.setValue(tkValue);
        } else {
            ck = new Cookie(ContextConstants.request_cookie_token, tkValue);
        }
        ck.setPath("/");
        response.addCookie(ck);
    }

    public static void invalidateUserLoginTokenCookie(HttpServletRequest request, HttpServletResponse response) {
        invalidateCookie(request, response, ContextConstants.request_cookie_token);
    }


    public static void invalidateCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
        Cookie ck = getCookie(request, cookieName);
        if (ck != null) {
            ck.setMaxAge(0);
            response.addCookie(ck);
        }
        request.getSession().invalidate();
    }

}
